package Models::ContentModel;

use lib 'd:/test_project/lib/';
use Models::db::Content;
use strict;
use DBI;

my $tablename = "content";
my $dbh;
my $query = {where => undef, select => undef, limit => undef, order =>undef};

	BEGIN {
		$dbh = DBI->connect('dbi:ODBC:driver={SQL Server};Server=localhost\SQLEXPRESS;database=testproject;uid=bohdan;pwd=test;',undef,undef,{ RaiseError => 0, AutoCommit => 0 })
				or print "Content-type: text/html\r\n\r\n connect failed: $DBI::errstr";
	}
	END {
		$dbh->disconnect();
	}

	sub new {
		my $check = shift;
		my $class = ref($check) || $check;
		my $self  = {
			statusNumber => undef,
			statusMsg    => undef,
			statusLogID  => undef,
			@_ # init
		};
		$self->{Rows} = undef;
		$self->{Columns} = undef;
		return bless($self, $class);
	}


	sub findPk {
		my ($self, $id) = @_;
		my $sth = $dbh->prepare("SELECT DISTINCT * FROM $tablename WHERE id=$id");
		$sth->execute();
		my $result = $sth->fetchrow_hashref();
		return Models::db::Menu->new($result);
	}
	
	sub filterByCode {
		my ($self, $code, $compare, $and) = @_;
		$compare = defined($compare) ? ' ' . $compare . ' ' : '=';
		if (defined($query->{where})) {
			$and = defined($and) ? $and : ' AND ';
		} else {
			$and = "";
		}
		$$query{where} = $query->{where} . ("$and code$compare'$code'");
		return $self;
	}

	sub findOne { 
		my ($self, $id) = @_;
		my $sth = $dbh->prepare("SELECT * FROM $tablename WHERE $query->{where}");
		$sth->execute();
		my $result = $sth->fetchrow_hashref();
		#print "Content-type: text/html\n\n", Dumper $result;
		return Models::db::Content->new($result);
	}

	sub getTableName {
		return $tablename;
	}

1;